<?php

declare(strict_types=1);

namespace app\api\controller\user;

use app\BaseController;


use app\common\model\User\User as UserModel;
use app\common\model\Config as ConfigModel;
use app\common\model\User\Record as RecordModel;
use app\common\model\User\Pay as PayModel;
use app\common\validate\User\User as UserValidate;
use think\exception\ValidateException;
use think\facade\Session;

class Base extends BaseController
{

    public function initialize()
    {
        parent::initialize();

        $this->UserModel = new UserModel();
        $this->ConfigModel = new ConfigModel();
        $this->RecordModel = new RecordModel();
        $this->PayModel = new PayModel();
    }

    // 登陆
    public function login()
    {

        if ($this->request->isPost()) {
            $email = $this->request->param('email', '');
            $password = $this->request->param('password', '');

            //查询 toArray 转换为数组
            $User = $this->UserModel->where(['email' => $email])->find();

            //当没有找到用户的情况下
            if (!$User) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            //密码盐
            $salt =  $User['salt'];

            //要让密码加密后做对比
            $password = md5(trim($password) . $salt);

            //判断密码
            if ($password != $User['password']) {

                $this->error('密码输入有误，请重新输入');
                exit;
            }

            //拼接返回的数据
            $data = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar' => $User['avatar_cdn'],
                'sex' => $User['sex'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'cover' => $User['cover_cdn'],
                'region' => $User['region_text'],
            ];

            //跳转界面
            $this->success('登录成功', '/user/base/index', $data);
            exit;
        }
    }

    // 验证是否登录
    public function check()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);

            $User = $this->UserModel->find($userid);

            if ($User) {
                //设置一个保存cookie信息
                $data = [
                    'id' => $User['id'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover' => $User['cover_cdn'],
                    'region' => $User['region_text'],
                ];

                $this->success('登录成功，存在用户', null, $data);
                exit;
            } else {
                $this->error('用户不存在');
                exit;
            }
        }
    }

    // 注册
    public function register()
    {
        if ($this->request->isPost()) {

            $email = $this->request->param('email', '');
            $password = $this->request->param('password', '');

            //查询邮箱
            $User = $this->UserModel->where(['email' => $email])->find();

            if ($User) {

                $this->error('该邮箱已注册，请重新输入');
                exit;
            }

            if (empty($password)) {
                $this->error('密码不能为空');
                exit;
            }

            //生成密码盐
            $salt = build_ranstr(10);

            //将密码和密码盐md5加密
            $password = md5(trim($password) . $salt);

            //获取系统配置表里面的赠送积分
            $RegisterPoint = $this->ConfigModel->where(['key' => 'RegisterPoint'])->value('value');

            //判断一下注册积分 是不是一个整数
            $RegisterPoint = is_numeric($RegisterPoint) ? abs($RegisterPoint) : 0;

            //组装数据
            $data = [
                'email' => $email,
                'password' => $password,
                'salt' => $salt,
                'nickname' => $email,
                'point' => $RegisterPoint,
                'vip' => 0,
                'auth' => 0
            ];

            try {
                validate(UserValidate::class)->check($data);
                //开始插入数据库 validate('common/User/User')
                $result = $this->UserModel->save($data);
            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }

            if ($result === FALSE) {
                //注册失败
                // code = 0
                // getError 返回操作的结果
                $this->error($this->UserModel->getError());
                halt();
            } else {
                //注册成功，跳转到登录界面
                // code = 1
                $this->success('注册成功');
                halt();
            }
        }
    }

    // 修改资料
    public function profile()
    {
        if ($this->request->isPost()) {

            //获取所有的参数
            $params = $this->request->param();

            $userid = $this->request->param('id', 0);
            $password = $this->request->param('password', '');

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'id' => $userid,
                'nickname' => $params['nickname'],
                'email' => $params['email'],
                'sex' => $params['sex'],
                'content' => $params['content'],
                // 'province' => $params['province'],
                // 'city' => $params['city'],
                // 'district' => $params['district'],
            ];


            if(empty($params['district'])){
                $data['district'] = $params['district'];
                $data['city'] = $params['city'];
                $data['province'] = $params['province'];
            }

            //密码不为空
            if (!empty($password)) {
                $salt = $user['salt'];

                $repass = md5($password . $salt);

                //判断新密码和旧密码是否一致
                if ($repass == $user['password']) {
                    $this->error('当前密码为旧密码，请重新输入');
                    exit;
                }

                //生成新的密码盐
                $newsalt = build_ranstr(10);

                //新密码加密
                $password = md5(trim($password) . $newsalt);

                $data['salt'] = $newsalt;
                $data['password'] = $password;
            }

            //判断头像
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $result = upload('avatar');

                if ($result === FALSE) {
                    $this->error('修改头像失败');
                    exit;
                }

                //追加头像
                $data['avatar'] = $result['data'];
            }

            //封面
            if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                $result = upload('cover');


                if ($result === FALSE) {
                    $this->error('修改封面失败');
                    exit;
                }

                //追加封面
                $data['cover'] = $result['data'];
            }

            //更新数据库
            $result = $this->UserModel->update($data);

            if ($result === FALSE) {
                //上传上来的图片删除了
                @is_file($data['avatar']) && @unlink($data['avatar']);

                @is_file($data['cover']) && @unlink($data['cover']);

                $this->error('修改个人资料失败');
                exit;
            } else {

                //先判断是否有选择新的图片
                if (isset($_FILES['avatar']) && @is_file($data['avatar'])) {
                    //修改成功后，将原来的图片删除
                    $avatar = ltrim($user['avatar'], "/");
                    @is_file($avatar) && @unlink($avatar);
                }

                //先判断是否有选择新的图片
                if (isset($_FILES['cover']) && @is_file($data['cover'])) {
                    //修改成功后，将原来的图片删除
                    $cover = ltrim($user['cover'], "/");
                    @is_file($cover) && @unlink($cover);
                }

                //直接查询最新的结果在返回
                $UserData = $this->UserModel->find($userid);

                $data = [
                    'id' => $UserData['id'],
                    'email' => $UserData['email'],
                    'nickname' => $UserData['nickname'],
                    'avatar' => $UserData['avatar_cdn'],
                    'sex' => $UserData['sex'],
                    'province' => $UserData['province'],
                    'city' => $UserData['city'],
                    'district' => $UserData['district'],
                    'createtime' => $UserData['createtime'],
                    'content' => $UserData['content'],
                    'point' => $UserData['point'],
                    'vip' => $UserData['vip'],
                    'auth' => $UserData['auth'],
                    'cover' => $UserData['cover_cdn'],
                    'region' => $UserData['region_text'],
                ];

                $this->success('修改资料成功', '/user/base/index', $data);
                exit;
            }
        }
    }

    // 消费记录
    public function record()
    {
        if ($this->request->isPost()) {

            //获取所有的参数
            $status = $this->request->param('status', '');

            $userid = $this->request->param('userid', 0);

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $where = [];

            $where['userid'] = $userid;

            if ($status == "vue") {
                $where['state'] = ['3', '5', '-1'];
            } else if ($status == "uniapp"){
                $where['state'] = ['6', '-2'];
            }

            $RecordList = $this->RecordModel->where($where)->order('createtime', 'desc')->select();

            //跳转界面
            $this->success('', null,  $RecordList);
            exit;
        }
    }

    // 充值
    public function recharge()
    {
        if ($this->request->isPost()) {

            //获取所有的参数
            $point = $this->request->param('point', 0);

            $userid = $this->request->param('userid', 0);

            $content = $this->request->param('content', '');

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $data = [
                'userid' => $userid,
                'point' => $point,
                'status' => 0,
                'content' => $content
            ]; 

            $result = $this->PayModel->save($data);

            if ($result === FALSE) {
               
                $this->error($this->PayModel->getError());
                exit;
            } else {
                
                $this->success('充值成功,待审核');
                exit;
            }

        }
    }

    // 充值记录
    public function rechargerecord()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $result = $this->PayModel->where(['userid' => $userid])->order('id', 'DESC')->select();

            if ($result === FALSE) {
               
                $this->error($this->PayModel->getError());
                exit;
            } else {
                
                $this->success('充值记录列表',null,$result);
                exit;
            }
        }
    }

    // 发送验证码
    public function email()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $salt = build_ranstr(4);
            
            Session::set("salt{$userid}",$salt);

            // 内容
            $msg = "帐号认证，验证码：$salt";


            $result = EmailSend($user['nickname'],$user['email'],$msg);

            if($result === FALSE)
            {
                $this->error('验证码发送失败');
            }else{
                $this->success('验证码发送成功，请去邮箱查看验证码', null , $salt);
            }
            
        }
    }

     // 校验验证码
     public function emailcode()
     {
         if ($this->request->isPost()) {
 
             $userid = $this->request->param('userid', 0);

             $code = $this->request->param('code', '', 'trim');
 
             $user = $this->UserModel->find($userid);
 
             if (!$user) {
                 $this->error('用户不存在');
                 exit;
             }
 
            $salt = Session::get("salt{$userid}");

            if($code != $salt)
            {
                $this->error('验证码错误，请重新获取');
                Session::delete("salt{$userid}");
                exit;
            }
            $data = [
                'id' => $userid,
                'auth' => 1
            ];

            //更新数据库
            $result = $this->UserModel->update($data);

           

            if($result === FALSE)
            {
                $this->error('认证失败,请稍后重试');
            }else{
               
                Session::delete("salt{$userid}");

                //直接查询最新的结果在返回
                $UserData = $this->UserModel->find($userid);

                $datas = [
                    'id' => $UserData['id'],
                    'email' => $UserData['email'],
                    'nickname' => $UserData['nickname'],
                    'avatar' => $UserData['avatar_cdn'],
                    'sex' => $UserData['sex'],
                    'province' => $UserData['province'],
                    'city' => $UserData['city'],
                    'district' => $UserData['district'],
                    'createtime' => $UserData['createtime'],
                    'content' => $UserData['content'],
                    'point' => $UserData['point'],
                    'vip' => $UserData['vip'],
                    'auth' => $UserData['auth'],
                    'cover' => $UserData['cover_cdn'],
                    'region' => $UserData['region_text'],
                ];

                $this->success('认证成功', null , $datas);
            }
         }
     }
}
